/**
 * file 转 base64 格式
 * @param file
 * @returns base64
 */
export const imgFile2Base64 = (file: File): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = function () {
      resolve(this.result as string)
    }
    reader.onerror = () => reject('图片文件转 base64 格式失败')
  })

type Opts = {
  maxWidth?: number
  quality?: number
}
/**
 * 压缩 base64 图片
 * @param base64 需要压缩的 base64 图片
 * @param Object.opts 配置项
 * @param Object.opts.max
 * @returns 压缩过后的 base64 图片
 */
export const compressBase64Img = (base64: string, opts: Opts): Promise<string> =>
  new Promise((resolve, reject) => {
    // 默认参数
    const { maxWidth, quality } = Object.assign({ maxWidth: 100, quality: 1 }, opts)

    const img = new Image()
    img.src = base64
    img.style.objectFit = 'cover'
    img.style.zIndex = '-999'
    img.style.position = 'fixed'
    img.onload = () => {
      document.body.appendChild(img)
      let { width, height } = img.getClientRects()[0]
      const scale = width / height
      width = width > maxWidth ? maxWidth : width
      height = width / scale
      const canvasEl = document.createElement('canvas')
      canvasEl.width = width
      canvasEl.height = height
      const canvasCtx = canvasEl.getContext('2d')
      if (!canvasCtx) return reject('生成 canvas 上下文失败')
      canvasCtx.drawImage(img, 0, 0, width, height)
      img.remove()
      resolve(canvasEl.toDataURL(undefined, quality))
    }
    img.onerror = () => reject('生成图片失败')
  })

/**
 * base64 转 file 类型
 * @param base64 base64字符串
 * @param fileName 文件名
 * @returns File
 */
export const base64ToFile = (base64: string, fileName: string) => {
  const arr = base64.split(',')
  const mime = arr[0].match(/:(.*?);/)![1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], fileName, { type: mime })
}

export const videoFile2Base64 = (file: File): Promise<string> =>
  new Promise((resolve, reject) => {
    const videoEl = document.createElement('video')
    videoEl.src = URL.createObjectURL(file)
    videoEl.style.objectFit = 'cover'
    videoEl.style.position = 'fixed'
    videoEl.style.zIndex = '-999'
    videoEl.currentTime = 0.1
    videoEl.onloadeddata = function () {
      const canvasEl = document.createElement('canvas')
      videoEl.oncanplay = () => {
        document.body.appendChild(videoEl)
        canvasEl.width = videoEl.clientWidth
        canvasEl.height = videoEl.clientHeight
        const canvasCtx = canvasEl.getContext('2d')
        if (!canvasCtx) return reject('生成 canvas 上下文失败')
        canvasCtx.drawImage(videoEl, 0, 0, videoEl.clientWidth, videoEl.clientHeight)
        resolve(canvasEl.toDataURL('image/jpeg'))
        videoEl.remove()
      }
    }
    videoEl.onerror = () => reject('视频文件生成缩略图失败')
  })
